package com.yzxb.messystem.service.impl;

import com.yzxb.messystem.entity.Product;
import com.yzxb.messystem.exception.BusinessException;
import com.yzxb.messystem.exception.ResourceNotFoundException;
import com.yzxb.messystem.mapper.ProductMapper;
import com.yzxb.messystem.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectList(null);
    }
    
    @Override
    public Optional<Product> getProductById(Long id) {
        Product product = productMapper.selectById(id);
        return Optional.ofNullable(product);
    }
    
    @Override
    public Optional<Product> getProductByCode(String productCode) {
        Product product = productMapper.findByProductCode(productCode);
        return Optional.ofNullable(product);
    }
    
    @Override
    public Product addProduct(Product product) {
        // 检查产品代码是否已存在
        if (productMapper.existsByProductCode(product.getProductCode()) > 0) {
            throw new BusinessException("产品代码已存在: " + product.getProductCode());
        }
        // 设置创建时间
        product.setCreateTimeDefault();
        productMapper.insert(product);
        return product;
    }
    
    @Override
    public Product updateProduct(Long id, Product product) {
        // 检查产品是否存在
        Product existingProduct = productMapper.selectById(id);
        if (existingProduct == null) {
            throw new ResourceNotFoundException("Product", "id", id);
        }
        
        // 更新产品信息
        existingProduct.setProductName(product.getProductName());
        existingProduct.setDescription(product.getDescription());
        existingProduct.setCategory(product.getCategory());
        existingProduct.setPrice(product.getPrice());
        existingProduct.setStockQuantity(product.getStockQuantity());
        // 设置更新时间
        existingProduct.setUpdateTimeDefault();
        
        productMapper.updateById(existingProduct);
        return existingProduct;
    }
    
    @Override
    public void deleteProduct(Long id) {
        // 检查产品是否存在
        if (productMapper.selectById(id) == null) {
            throw new ResourceNotFoundException("Product", "id", id);
        }
        productMapper.deleteByProductCode(id.toString());
    }
    
    @Override
    public List<Product> getProductsByCategory(String category) {
        return productMapper.findByCategory(category);
    }
    
    @Override
    public List<Product> searchProductsByName(String keyword) {
        return productMapper.findByProductNameContaining(keyword);
    }
}